package com.suman.bbcticker.configure;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.suman.bbcticker.Eula;
import com.suman.bbcticker.R;
import com.suman.bbcticker.activity.WrongLaunchAlertActivity;
import com.suman.bbcticker.widget.SkyNewsReaderAppWidget;

public class PreferenceLauncherActivity extends Activity {
	private static final String TAG = "PreferenceLauncherActivity";
	public static final String PREFS_NAME = "com.suman.rss.configure.PreferenceLauncherActivity";
	public static final String TICKER_ALERTTYPE_SOUND_KEY = "ticker_alerttype_sound_key";
	public static final String TICKER_ALERTTYPE_VIBRATE_KEY = "ticker_alerttype_vibrate_key";
	public static final String TICKER_ALERTTYPE_NOTIFICATION_KEY = "ticker_alerttype_notification_key";
	public static final String TICKER_ALERTTYPE_SITESELECTED_KEY = "ticker_selectedsite_key";
	public static final String TICKER_ALERTTYPE_FEEDREFRESHTIME_KEY = "ticker_feedrefreshtime_key";

	public static final String PREF_PREFIX_KEY = "prefix_";
	private int mAppWidgetId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// get any data we were launched with
		Intent launchIntent = getIntent();
		Bundle extras = launchIntent.getExtras();
		if (extras == null) {
			Intent cancelResultValue = new Intent();
			cancelResultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
			setResult(RESULT_CANCELED, cancelResultValue);
			
			Intent intent = new Intent();
			intent.setClass(this, WrongLaunchAlertActivity.class);
			startActivity(intent);
			
			finish();
		} else {
			mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

			Intent cancelResultValue = new Intent();
			cancelResultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
			setResult(RESULT_CANCELED, cancelResultValue);
			if (Intent.ACTION_MAIN.equalsIgnoreCase(launchIntent.getAction()) && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)) {

				Intent intent = new Intent();
				intent.setClass(this, WrongLaunchAlertActivity.class);
				startActivity(intent);
				
				finish();
			} else {
		
				Intent launchPreferencesIntent = new Intent().setClass(this, FeedTickerPreferences.class);
				startActivityForResult(launchPreferencesIntent, mAppWidgetId);
			}
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		 final SharedPreferences preferences = getSharedPreferences(Eula.PREFERENCES_EULA,Activity.MODE_PRIVATE);
	        if (!preferences.getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)){
	        	finish();
	        	
	        }else{
	        	if (requestCode == mAppWidgetId) {
	    			// TODO put default values for each preferences in xml
	    			// And update description to talk abt default values..again in xml
	    			// And raise a toast saying preferences have been saved
	    			Toast.makeText(this, "Your Preferences have been Saved"
	                       , Toast.LENGTH_SHORT).show();
	    			
	    			
	    			
	    			configureAlarm();
	    			setResultForActivity();
	    			savePreferenceAsString(this, PREF_PREFIX_KEY + mAppWidgetId, "saved");
	    			updateRemoteViewWithLoadingMessage(this, mAppWidgetId);
	    		}
	        	
	        }
		

	}

	private void configureAlarm() {
		Intent widgetUpdate = new Intent(this, SkyNewsReaderAppWidget.class);
		widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { mAppWidgetId });
		widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
		widgetUpdate.putExtra("unique", "unique");

		// make this pending intent unique
		widgetUpdate.setData(Uri.withAppendedPath(Uri.parse(SkyNewsReaderAppWidget.URI_SCHEME + "://widget/id/"), String
				.valueOf(mAppWidgetId)));
		PendingIntent newPending = PendingIntent.getBroadcast(getApplicationContext(), 0, widgetUpdate, PendingIntent.FLAG_UPDATE_CURRENT);

		// schedule the new widget for updating
		AlarmManager alarms = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
		int updateRateInMins = Integer.parseInt("1");
		alarms.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), updateRateInMins * 1000 * 60, newPending);

	}

	private void setResultForActivity() {
		Intent resultValue = new Intent();
		resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
		setResult(RESULT_OK, resultValue);
	}

	private void updateRemoteViewWithLoadingMessage(Context context, int appWidgetId) {
		RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_word);
		updateViews.setTextViewText(R.id.word_title, "Loading...Trying to connect to network...Please Wait.Thank You For Your Patience.");
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		manager.updateAppWidget(mAppWidgetId, updateViews);
		finish();
	}

	private static void savePreferenceAsString(Context context, String key, String text) {
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		SharedPreferences.Editor prefs = sharedPreferences.edit();
		prefs.putString(key, text);
		prefs.commit();
	}

}
